var express=require('express');
var path = require('path');
var fs = require('fs');
var url = require('url');
// var cors = require('cors'); 

var tools=require('../utils/tools');
var user_map=require('../utils/userMap');
var checkCode_map=require('../utils/checkCodeMap');
var handle_manager=require('./handle_manager');

var app=express();

// console.log(path.join(__dirname, '../static'));

app.use(express.static(path.join(__dirname, '../static')));
// app.use(express.static(path.join(__dirname, '../static/images/gameico'))); //设置正确的路径后，服务器监听不到请求
// app.use(cors());

var hallAddr='';

var config=null;
var codes_dir='./codes';
exports.start=function(cfg){
    user_map.init(cfg.time_count);
    checkCode_map.init(cfg.time_count,codes_dir);
    config=cfg;
    hallAddr=config.hall_ip+":"+config.hall_client_port;
    app.listen(config.client_port);
    console.log('account-----'+config.hall_ip+":"+config.client_port);
};

//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    if (req.method == 'OPTIONS') {
        res.send(200);
    } 
    var pathname=url.parse(req.url).pathname;
    var extname=path.extname(pathname);
    // console.log('***************** '+req.url,pathname,extname);
    if(extname==''){
        res.header("Content-Type", "application/json;charset=utf-8");
        next();
    }else{
        //加载静态文件
        other_req(req,res);
    }
   
});

//加载静态文件 不能设置正确的路径 不然直接返回了，监听不到请求
function other_req(req,res){
    var pathname=url.parse(req.url).pathname;
    // console.log('pathname '+pathname);
    var extname=path.extname(pathname);
    // console.log('extname '+extname);
    var dirname='';
    if(pathname=='/'){
        dirname=path.join(__dirname, '..\\static','html','index.html');
    }else{
        if(extname=='.css'){
            dirname=path.join(__dirname, '..\\static','css',pathname);
        }else if(extname=='.js'){
            dirname=path.join(__dirname, '..\\static','js',pathname);
        }else if(extname in {'.png':'','.gif':''}){//images/gameico/
            dirname=path.join(__dirname, '..\\static','images','gameico',pathname);
        }
        else{
            dirname=path.join(__dirname, '..\\static',pathname);
        }
    }
    // console.log(dirname);
    get_file_content(dirname,function(err,data){
        if(err){
            get_file_content(path.join(__dirname, '..\\static','html','404.html'),function(err,data404){
                res.writeHead(404,{"Content-Type":"text/html;charset='utf-8'"});
                res.write(data404);
                res.end();
            });
        }else{
            tools.getMime(fs,path,extname,function(mime){
                res.writeHead(200,{"Content-Type":"" + mime + ";charset='utf-8'"});
                res.write(data);
                res.end();
            });
        }
    });
};

app.all('/',function(req,res){
    other_req(req,res);
});

function get_file_content(filepath,callback) {
    return fs.readFile(filepath,callback);
}

app.post('/Use',function(req,res){
    tools.data_parser(req,function(json){
        handle_manager.use_func(res,json);
    });
});

app.get('/Login',function(req,res){
    var query=req.query;
    // console.log(query);
    switch(query.a){
        case 'checkCode':
        {
            handle_manager.checkCode_func(res,query);
        }
        break;
    }
});

app.get('/Game',function(req,res){
    var query=req.query;
    // console.log(query);
    switch(query.a){
        case 'online':
        {
            handle_manager.online_func(res,query);
        }
        break;
        case 'GetPublic':
        {
            handle_manager.GetPublic_func(res,query);
        }
        break;
        case 'GetGameList':
        {
            handle_manager.GetGameList_func(res,query);
        }
        break;
        case 'GetEnjoyGames':
        {
            handle_manager.GetEnjoyGames_func(res,query);
        }
        break;
    }
});

app.post('/Game',function(req,res){
    var query=req.query;
    // console.log(query);
    tools.data_parser(req,function(json){
        switch(query.a){
            case 'login':
            {
                handle_manager.login_func(res,json,query);
            }
            break;
            case 'UseSaveLoveGames':
            {
                handle_manager.UseSaveLoveGames_func(res,json,query);
            }
            break;
        }
    });
});

